
// pages/upinfo/upinfo.js
var util = require('../../utils/util')
var DATE = util.formatDate(new Date())
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
//var uploadImage = require('../../utils/uploadImg/uploadImgnew.js');//地址换成你自己存放文件的位置
var qqmapsdk = new QQMapWX({
  //key: 'U47BZ-NJBK3-LZB3B-3YAQR-564JQ-XVF7N' // 必填
  //key: '5PNBZ-MTTWQ-HCJ5Z-4FPNH-6H2GT-L3FGT'
  key: 'VZHBZ-6BYWU-WCPVE-2NRJV-YZKXZ-GEFT4'
});
var api = require('../../config/api.js');


Page({

  /**
   * 页面的初始数据
   */
  data: {


    //推荐区域

    suggestTypeItems: [
      { value: 1, code: 'cdsqzyq', name: '成都输气作业区' },
      { value: 2, code: 'rssqzyq', name: '仁寿输气作业区' },
      { value: 3, code: 'zgsqzyq', name: '自贡输气作业区' },
      { value: 4, code: 'ylsqzyq', name: '仪陇输气作业区' },
      { value: 5, code: 'ncsqzyq', name: '南充输气作业区' },
      { value: 6, code: 'lpsqzyq', name: '梁平输气作业区' },
      { value: 7, code: 'cqsqzyq', name: '重庆输气作业区' },
      { value: 8, code: 'hjsqzyq', name: '合江输气作业区' },
      { value: 9, code: 'mygdglb', name: '绵阳管道管理部' },
      { value: 10, code: 'cpgdglb', name: '楚攀管道管理部' }

    ],
    indexsuggestType: 0,
    //人员类型

    userTypeItems: [
      { value: 1, code: '管道周边村民', name: '管道周边村民' },
      { value: 2, code: '物权人', name: '物权人' },
      { value: 3, code: '关联企业', name: '关联企业' },
      { value: 4, code: '挖机手', name: '挖机手' },
      { value: 5, code: '核心人员', name: '核心人员' },
      { value: 6, code: '发改局', name: '发改局' },
      { value: 7, code: '交通局', name: '交通局' },
      { value: 8, code: '农业农村局', name: '农业农村局' },
      { value: 9, code: '自然规划局', name: '自然规划局' },
      { value: 10, code: '水利局', name: '水利局' },
      { value: 11, code: '电力局', name: '电力局' },
      { value: 12, code: '基层组织', name: '基层组织' },
      { value: 13, code: '政府部门', name: '政府部门' }
    ],
    indexuserType: 0,



    region: ["四川省", "成都市", "锦江区"],

    //上报信息
    userDto: {
      nickName: '',
      phone: '',

      address: '',
      province: '',
      city: '',
      district: '',
      longitude: 0,
      latitude: 0,
      suggestCode: '',
      userType: '普通村民'





    },


  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //获取地址
    this.getCurrentLocal()
    //获取当前数据库用户
    this.inituser();

  },

  /**
   * 生命周期函数--监听页面显示
   */


  bindsuggest(event) {
    let index = event.detail.value;
    this.data.userDto.suggestCode = this.data.suggestTypeItems[index].code
    this.setData({
      indexsuggestType: index
    })


  },

  binduser(event) {
    let index = event.detail.value;
    this.data.userDto.userType = this.data.userTypeItems[index].code
    this.setData({
      indexuserType: index
    })


  },


  //.js
  //点击确定按钮
  bindRegionChange: function (e) {
    console.log(e)
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
    this.data.userDto.province = this.data.region[0];
    this.data.userDto.city = this.data.region[1];
    this.data.userDto.district = this.data.region[2];

  },


  //初始化用户
  inituser() {
    var userinfo = wx.getStorageSync('userInfoDto');
    console.log(userinfo)
    if (typeof (userinfo.userName) != "undefined") {
      this.setData({
        ['userDto.nickName']: userinfo.userName,
      })
    }
    if (typeof (userinfo.phone) != "undefined") {
      this.setData({
        ['userDto.phone']: userinfo.phone,
      })
    }
    if (typeof (userinfo.province) != "undefined") {
      this.setData({
        ['userDto.province']: userinfo.province,
      })
    }
    if (typeof (userinfo.city) != "undefined") {
      this.setData({
        ['userDto.city']: userinfo.city,
      })
    }
    if (typeof (userinfo.district) != "undefined") {
      this.setData({
        ['userDto.district']: userinfo.district,
      })
    }
    if (typeof (userinfo.address) != "undefined") {
      this.setData({
        ['userDto.address']: userinfo.address,
      })
    }

  },


  //获取手机号
  getPhoneNumber(e) {
    let that = this;
    var code = e.detail.code;
    console.log(e)
    var accessTokenwrtie = wx.getStorageSync("accessToken");
    var requestDate = { phoneCode: code, accessToken: accessTokenwrtie }
    util.request(api.getWechatPhone, JSON.stringify(requestDate), 'POST').then(function (res) {
      console.log(res)
      if (res.code == 200) {
        console.log(res.data)
        that.setData({
          ['userDto.phone']: res.data
        })

      } else {
        util.showErrorToast(res.message);
      }

    }).catch((err) => {
      console.log("登录远程服务器catch:" + err);
      //reject(err);
    });



  },

  //用户名称
  bindinputnickname(event) {
    this.data.userDto.nickName = event.detail.value
  },


  //用户电话
  bindinputphone(event) {
    this.data.userDto.phone = event.detail.value
  },
  //详细地址
  bindAddressinput(event) {
    this.data.userDto.address = event.detail.value
  },






  //---------------提交数据----------------------//

  /**
     * 校验
     */
  checkValue() {
    let dataup = this.data;
    if (dataup.userDto.nickName === '' || dataup.userDto.nickName == null) {
      util.showErrorToast('请填写姓名');
      return false
    }
    if (dataup.userDto.phone === '' || dataup.userDto.phone === null) {
      util.showErrorToast('请填写电话');
      return false
    }

    const phoneReg = /^1[3-9]\d{9}$/; // 支持最新号段（如19x）
    if (!phoneReg.test(dataup.userDto.phone)) {
      util.showErrorToast("手机号格式错误");
      return false;
    }

    // if (this.data.localname == '' || this.data.localname == null) {
    //     util.showErrorToast('未获取到正确地址，请稍后再试');
    //     return false
    // }

    if (dataup.userDto.city == '' || dataup.userDto.city == null) {
      util.showErrorToast('未获取到正确地址，请稍后再试');
      return false
    }
    if (dataup.userDto.district == '' || dataup.userDto.district == null) {
      util.showErrorToast('未获取到正确地址，请稍后再试');
      return false
    }

    if (dataup.userDto.province == '' || dataup.userDto.province == null) {
      util.showErrorToast('未获取到正确地址，请稍后再试');
      return false
    }

    return true
  },


  //保存提交
  save() {

    if (!this.checkValue()) {
      //this.loadModal();
      return
    }
    this.loadup();

  },

  //上报数据
  loadup() {
    //提交上报数据
    let dataup = this.data.userDto;
    let that = this;
    console.log(JSON.stringify(dataup))
    that.loadModal();
    util.request(api.editUserInfo, JSON.stringify(dataup), 'POST').then(function (res) {
      console.log(res)
      if (res.code == 200) {
        //更新内部存储信息
        wx.setStorageSync('userInfoDto', res.data)
        that.closeModal();
        //刷新界面
        console.log("========")
        wx.showModal({
          title: '注册成功!',
          content: '感谢您对我们在管道保护工作中所做出的贡献和支持。',
          confirmText: '确定',
          success: res => {
            //刷新界面
            wx.navigateBack({})
          }
        })

      } else {
        util.showErrorToast(res.message);
      }

    }).catch((err) => {
      that.closeModal();
      console.log("登录远程服务器catch:" + err);
      //reject(err);
    });


  },





  //进度条
  loadModal() {
    this.setData({
      loadModal: true
    })
  },
  closeModal() {
    this.setData({
      loadModal: false
    })
  },



  //--------------------------地址位置----------//


  //刷新地址
  refreshLocal(e) {

    this.setData({
      modalName: e.currentTarget.dataset.target
    })

    this.getCurrentLocal()
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },



  // 获取当前地理位置 授权验证
  getCurrentLocal() {

    let that = this;
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userLocation'] == false) {// 如果已拒绝授权，则打开设置页面
          wx.openSetting({
            success(res) {

            }
          })
        } else { // 第一次授权，或者已授权，直接调用相关api
          that.getMyLocation()

        }
      }
    })
  },
  // 获取当前地理位置
  getMyLocation() {
    let that = this

    wx.getLocation({
      type: 'gcj02',
      altitude: true,
      isHighAccuracy: true,
      success(res) {
        that.getlocalname(res.latitude, res.longitude)
        that.setData({
          modalValue: '刷新定位成功'
        })
      },
      fail(res) {
        that.setData({
          modalValue: '刷新频率过高'
        })
        console.log(res)
      }
    })
  },

  //获取物理地址
  getlocalname(latitude, longitude) {
    let that = this
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      policy: 1,
      success: function (res) {
        that.data.userDto.province = res.result.address_component.province;
        that.data.userDto.city = res.result.address_component.city;
        that.data.userDto.district = res.result.address_component.district;
        that.data.userDto.street = res.result.address_component.street_number;

        that.data.userDto.latitude = latitude;
        that.data.userDto.longitude = longitude;

        //that.data.userDto.address = res.result.address + res.result.formatted_addresses.recommend;

        //填入缓存
        that.setData({
          localname: res.result.address + res.result.formatted_addresses.recommend,
          region: [that.data.userDto.province, that.data.userDto.city, that.data.userDto.district],
          ['userDto.address']: res.result.formatted_addresses.recommend
        })
      },
      fail: function (error) {
        //填入缓存
        that.setData({
          region: ["四川省", "成都市", "锦江区"]
        })
        console.error(error);
      }
    })
  },


})